package com.navinfo.tripanalysis.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 通用工具类
 *
 * @author 马驰
 * @modify
 */

public class CommonUtils {

    /**
     * 通过split分割str
     * @param str
     * @param split
     * @return
     */
    public static List<String> splitStr(String str, String split) {
        List<String> list = new ArrayList<>();
        if (str != null) {
            String[] ss = str.split(split);
            for (String f : ss) {
                list.add(f.trim());
            }
        }
        return list;
    }

    /**
     * 将list中的数据toString后用split作为分隔符，返回一个大的字符串
     * @param list
     * @param split
     * @return
     */
    public static String mkString(Collection<?> list, String split) {
        StringBuilder stringBuilder = new StringBuilder();

        if(null!=list && list.size()>0){
            int i = 0;
            for (Object obj : list) {
                if (null != obj) {
                    if (i != 0) {
                        stringBuilder.append(split);
                    }
                    stringBuilder.append(obj);
                    i++;
                }
            }
        }

        return stringBuilder.toString();
    }

    /**
     * 判断集合是否为空
     * @param collection
     * @return
     */
    public static boolean isCollectionEmpty(Collection<?> collection) {
        return collection == null || collection.size() == 0;
    }

    /**
     * 判断集合不为空
     *
     * @param collection
     * @return
     */
    public static boolean isCollectionNotEmpty(Collection<?> collection) {
        return !isCollectionEmpty(collection);
    }

    /**
     * 获取异常的堆栈信息.
     *
     * @param t 异常
     * @return String
     */
    public static String getStackTrace(Throwable t, int maxLength) {
        if (maxLength == 0) {
            return "";
        }
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            t.printStackTrace(pw);
            if (sw.toString().length() <= maxLength) {
                return sw.toString();
            }
            return sw.toString().substring(0, maxLength - 1);
        } finally {
            pw.close();
        }
    }

}
